/*
 * @Copyright: Citylife 2021
 * @Author: WangXinnong
 * @Date: 2020-12-14 12:48:48
 * @Description: DialogManager
 */
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../theme/theme_manager.dart';
import 'dialog_info.dart';

class DialogManager {
  static DialogManager get instance => _getInstance();
  static DialogManager _instance;
  DialogManager._internal();
  static DialogManager _getInstance() {
    if (_instance == null) {
      _instance = DialogManager._internal();
    }
    return _instance;
  }

  //当前显示弹框
  DialogInfo _currentDialogInfo;
  //弹窗数据（待显示）
  List<DialogInfo> _recoverList = [];

  ///增加并显示弹框
  addDialog(DialogInfo info) async {
    print('#####addDialog: $info');
    //如果当前有弹框显示并且为最高级，则什么也不做
    if (_currentDialogInfo?.dialogLevel == CLDialogLevel.high) return;

    if (_currentDialogInfo == null) {
      _showDialogView(info);
    } else {
      if (info.extra != null) {
        //如果旧的extra的值和新的不一样，添加旧的dialog到恢复队列，否则旧的直接抛弃
        if (_currentDialogInfo.extra != null &&
            _currentDialogInfo.extra != info.extra) {
          _recoverList.add(_currentDialogInfo);
          //如果_recoverList包含相同extra字段的，则删除之前添加的
          int index = _recoverList.indexWhere((e) => (e.extra == info.extra));
          if (index != -1) {
            _recoverList.removeAt(index);
          }
        }
      }

      //添加最新的dialog到队列中
      _recoverList.add(info);

      //隐藏旧弹窗 // TODO
      dismiss();
    }

    //如有hignLevel，清空恢复列表
    if (info.dialogLevel == CLDialogLevel.high) {
      if (_recoverList.isNotEmpty) {
        _recoverList.clear();
      }
    }
  }

  ///外部调用DialogManager.instance.dismiss(context)，使弹框消失
  dismiss() {
    Navigator.of(Get.context, rootNavigator: true).pop();
  }

  ///dismiss监听
  _onDismiss() {
    _currentDialogInfo = null;
    if (_recoverList.isNotEmpty) {
      _showDialogView(_recoverList.last);
      _recoverList.remove(_recoverList.last);
    }
  }

  ///显示弹框
  _showDialogView(DialogInfo info) {
    _currentDialogInfo = info;

    switch (info.animationType) {
      case CLDialogAnimationType.center:
        Get.dialog(
          DialogScaleAnimation(info.dialogWidget()),
          barrierDismissible: false,
          barrierColor: theme.colors.dialogBackgroundColor,
        ).then((value) => _onDismiss());
        break;
      case CLDialogAnimationType.bottom:
        Get.bottomSheet(
          info.dialogWidget(),
          backgroundColor: Colors.transparent,
          useRootNavigator: true,
          barrierColor: theme.colors.dialogBackgroundColor,
          isDismissible: info.isDismissible,
          enableDrag: info.enableDrag,
        ).then((value) => _onDismiss());
        break;
    }
  }
}

class DialogScaleAnimation extends StatefulWidget {
  final Widget child;

  const DialogScaleAnimation(this.child);
  @override
  _DialogScaleAnimationState createState() => _DialogScaleAnimationState();
}

class _DialogScaleAnimationState extends State<DialogScaleAnimation>
    with SingleTickerProviderStateMixin {
  ///动画控制器
  AnimationController controller;
  AnimationStatusListener listener;
  @override
  void initState() {
    super.initState();
    animationController();
  }

  animationController() {
    controller = AnimationController(
        duration: const Duration(milliseconds: 200), vsync: this);
    listener = (AnimationStatus status) {
      print("动画还在监听中");
    };

    controller.forward();
    controller.addStatusListener(listener);
  }

  @override
  void dispose() {
    super.dispose();
    controller.removeStatusListener(listener);
    controller.dispose();
    controller = null;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Center(
        child: ScaleTransition(
          ///设置动画的缩放中心
          alignment: Alignment.center,

          ///动画控制器
          scale: controller,

          ///将要执行动画的子view
          child: widget.child,
        ),
      ),
    );
  }
}
